/*
 *
 * File Name          :  Sound.c
 * Description        :  Sound Functions
 */

#include <stdio.h>
#include "Sound.h"
#include "Hrtf.h"
#include "HrtfArray.h"

//#define SINWAVE_STEREO
#define MAX_SIGNAL 1.0

int8_t _Sound_fEOF = 0; //FlagEndOfFile
float _Sound_AudioBuffer[SOUND_BUFFER_LENGTH];
HRTF_StereoSignal _Sound_StereoSignal;

int16_t Sound_Init(void) {
  HRTF_Init();
  return 1;
}

const int16_t _Sound_Sinwave [] =
{
#include "Sinwave.h"
};

float *Sound_Get_AudioBuffer(void) { 
  return _Sound_AudioBuffer;
}

int32_t Sound_Get_AudioBuffer_Size(void) { 
  return sizeof(_Sound_AudioBuffer);
}

int32_t Sound_Position(float *dest, const int16_t *src, int32_t destLength, int32_t srcLength) { 
  int32_t i, currentPos;
  float sig;
  
  HRTF_SoundPosition(&_Sound_StereoSignal, (FPComplex *) src, srcLength, 0, -45);
  
  currentPos = 0;
  for(i=0; i<srcLength; i++) {
    sig = _Sound_StereoSignal.left[i][0]/100.0;
    if(sig>MAX_SIGNAL)
      sig = MAX_SIGNAL;
    dest[currentPos] = sig;
    currentPos++;
    
    sig = _Sound_StereoSignal.right[i][0]/100.0;
    if(sig>MAX_SIGNAL)
      sig = MAX_SIGNAL;
    dest[currentPos] = sig;
    currentPos++;
  }
  return currentPos;
}

int32_t Sound_FillBuffer(void) {
  int32_t half_audio_buffer = SOUND_BUFFER_LENGTH/2;
  
  Sound_Position(_Sound_AudioBuffer, _Sound_Sinwave, half_audio_buffer, DSP_FFT_SAMPLE_LENGTH);    
  return 0;
}
